package com.hpeng.util;

import java.awt.Graphics2D;   
import java.awt.RenderingHints;   
import java.awt.image.BufferedImage;   
import java.io.IOException;   
   
import javax.imageio.ImageIO;   
import javax.servlet.ServletException;   
import javax.servlet.ServletOutputStream;   
import javax.servlet.http.HttpServlet;   
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.http.HttpServletResponse;   

import org.springframework.stereotype.Component;
   
import com.sun.image.codec.jpeg.JPEGCodec;   
import com.sun.image.codec.jpeg.JPEGEncodeParam;   
import com.sun.image.codec.jpeg.JPEGImageEncoder;   
   
/** 
* ���Servlet����ͼ��ҳ�洫���ĵ���ͼƬ���� 
* 
* @author ����� 
* 
*/   
@Component("exportImage")  
@SuppressWarnings("serial")  
public class ExportImage extends HttpServlet {   
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)   
            throws ServletException, IOException {   
        this.doPost(request, response);   
     }   
   
    public void doPost(HttpServletRequest request, HttpServletResponse response)   
            throws ServletException, IOException {   
        int width = Integer.parseInt(request.getParameter("width"));   
        int height = Integer.parseInt(request.getParameter("height"));   
   
         BufferedImage result = new BufferedImage(width, height,   
                 BufferedImage.TYPE_INT_RGB);   
        for (int y = 0; y < height; y++) {   
            int x = 0;   
             String[] row = request.getParameter("r" + y).split(",");   
            for (int c = 0; c < row.length; c++) {   
                 String[] pixel = row[c].split(":");
                int repeat = pixel.length > 1 ? Integer.parseInt(pixel[1]) : 1;   
                for (int l = 0; l < repeat; l++) {   
                     result.setRGB(x, y, Integer.parseInt(pixel[0], 16));   
                     x++;   
                 }   
             }   
         }   
         response.setContentType("image/jpeg");   
         response.addHeader("Content-Disposition",   
                "attachment; filename=\"pie.jpg\"");   
         Graphics2D g = result.createGraphics();
         g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,   
                 RenderingHints.VALUE_ANTIALIAS_ON);   
         g.drawImage(result, 0, 0, width, height, null);   
         g.dispose();   
   
         ServletOutputStream f = response.getOutputStream();   
         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(f);   
         JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(result);   
         param.setQuality((float) (100 / 100.0), true);
         encoder.encode(result, param);   
         ImageIO.write(result, "JPEG", response.getOutputStream());
         f.close();   
     }   
   
} 


